package com.ruoyi.js.utils;

import com.ruoyi.common.config.Global;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.File;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;

/**
 *
 * Poi 工具类
 *
 */
public class PoiUtils {


    /**
     * 编码文件名
     */
    public static String encodingFilename(String filename, String ext)
    {
        filename = UUID.randomUUID().toString() + "_" + filename + ext;
        filename = filename.replaceAll("、", "");
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public static String getAbsoluteFile(String filename)
    {
        String downloadPath = Global.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 获取单元格值
     *
     * @param row 获取的行
     * @param column 获取单元格列号
     * @return 单元格值
     */
    public static Object getCellValue(Row row, int column)
    {
        if (row == null)
        {
            return row;
        }
        Object val = "";
        try
        {
            Cell cell = row.getCell(column);
            if (cell != null)
            {
                if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
                {
                    val = cell.getNumericCellValue();
                    if (HSSFDateUtil.isCellDateFormatted(cell))
                    {
                        val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                    }
                    else
                    {
                        if ((Double) val % 1 > 0)
                        {
                            val = new DecimalFormat("0.00").format(val);
                        }
                        else
                        {
                            val = new DecimalFormat("0").format(val);
                        }
                    }
                }
                else if (cell.getCellTypeEnum() == CellType.STRING)
                {
                    val = cell.getStringCellValue();
                }
                else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
                {
                    val = cell.getBooleanCellValue();
                }
                else if (cell.getCellTypeEnum() == CellType.ERROR)
                {
                    val = cell.getErrorCellValue();
                }

            }
        }
        catch (Exception e)
        {
            return val;
        }
        return val;
    }


    public static void setTableColumnsWidth(XWPFTable table, long... widths) {
        for (int i = 0; i < table.getNumberOfRows(); i++) {
            XWPFTableRow row = table.getRow(i);
            int numCells = row.getTableCells().size();
            if(numCells == widths.length){
                for (int j = 0; j < numCells; j++) {
                    XWPFTableCell cell = row.getCell(j);
                    CTTblWidth cellWidth = cell.getCTTc().addNewTcPr().addNewTcW();
                    CTTcPr pr = cell.getCTTc().addNewTcPr();
                    pr.addNewNoWrap();
                    cellWidth.setW(BigInteger.valueOf(widths[j]));
                }
            }else {
                throw new RuntimeException("表格宽度数据和表格列数不匹配");
            }

        }
    }

    public static void setTableRowsHeight(XWPFTable table, long... heights) {
        List<XWPFTableRow> rows = table.getRows();
        if(rows.size() == heights.length){
            for (int i = 0; i < rows.size(); i++) {
                CTTrPr trPr = rows.get(i).getCtRow().addNewTrPr();
                CTHeight ht = trPr.addNewTrHeight();
                ht.setVal(BigInteger.valueOf(heights[i]));
            }
        }else {
            throw new RuntimeException("表格行高数据和表格行数不匹配");
        }
    }

    /**
     *  word 表格设置单元格内容
     * @param cell
     * @param value
     * @param fontSize
     */
    public static void setCell(XWPFTableCell cell, Object value, int fontSize) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        String text = value != null ? value.toString() : "";
        run.setText(text);
        run.setFontSize(fontSize);
        run.setFontFamily("黑体");
    }

    /**
     * word 表格设置单元格内容
     * @param cell
     * @param value
     * @param fontSize
     * @param color
     */
    public static void setCell(XWPFTableCell cell, Object value, int fontSize, String color) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        XWPFRun run = paragraph.createRun();
        String text = value != null ? value.toString() : "";
        run.setText(text);
        run.setFontSize(fontSize);
        run.setFontFamily("黑体");
        run.setColor(color);
    }

    /**
     * word单元格列合并
     * @param table 表格
     * @param row 合并列所在行
     * @param startCell 开始列
     * @param endCell 结束列
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int startCell, int endCell) {
        for (int i = startCell; i <= endCell; i++) {
            XWPFTableCell cell = table.getRow(row).getCell(i);
            if (i == startCell) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * word单元格行合并
     * @param table 表格
     * @param col 合并行所在列
     * @param startRow 开始行
     * @param endRow 结束行
     */
    public static void mergeCellsVertically(XWPFTable table, int col, int startRow, int endRow) {
        for (int i = startRow; i <= endRow; i++) {
            XWPFTableCell cell = table.getRow(i).getCell(col);
            if (i == startRow) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    public static void setOrientAndMargin(XWPFDocument document, int orient, int top, int right, int bottom, int left){
        CTBody body = document.getDocument().getBody();
        CTSectPr sectPr = body.addNewSectPr();

        CTPageSz pgSz = sectPr.addNewPgSz();
        if(orient == 0){
            pgSz.setW(BigInteger.valueOf(11907));
            pgSz.setH(BigInteger.valueOf(16840));
        }else {
            pgSz.setW(BigInteger.valueOf(16840));
            pgSz.setH(BigInteger.valueOf(11907));
        }

        pgSz.setOrient(orient == 0 ? STPageOrientation.PORTRAIT : STPageOrientation.LANDSCAPE);

        CTPageMar pageMar = sectPr.addNewPgMar();
        pageMar.setTop(BigInteger.valueOf(top));
        pageMar.setRight(BigInteger.valueOf(right));
        pageMar.setBottom(BigInteger.valueOf(bottom));
        pageMar.setLeft(BigInteger.valueOf(left));
    }


    /**
     * word 段落文字
     * @param text
     * @return
     */
    public static void setParagraphText(XWPFRun run, String text){
        if(text == null){
            return;
        }
        String[] texts = text.split("\n");
        for (int i = 0; i < texts.length; i++) {
            run.addTab();
            texts[i] = texts[i].replace("\r", "").replace("\n", "");
            run.setText(texts[i]);
            if(i != texts.length - 1){
                run.addCarriageReturn();
            }
        }
    }


}